package com.wiz.web.controllor;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.annotation.Resource;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import sun.misc.BASE64Decoder;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.wiz.common.Constant;
import com.wiz.common.RedisConstant;
import com.wiz.common.ResponseCode;
import com.wiz.common.util.ThreeDESUtil;
import com.wiz.web.dao.mapper.LoginMapper;
import com.wiz.web.manager.RedisManager;
import com.wiz.web.vo.to.StationLoginTO;

@SuppressWarnings("all")
public abstract class BaseControllor implements ResponseCode,RedisConstant,Constant {

	//满足linux环境下需求
	protected Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
	
	@Resource
	protected RedisManager redisManager;
	@Resource
	protected LoginMapper loginMapper;
	
	protected byte[] keyiv = { 1, 2, 3, 4, 5, 6, 7, 8 };
	
	/**
	 * 解密参数信息
	 * @param stationId
	 * @param paramStr
	 * @return
	 * @throws Exception 
	 * @throws BadPaddingException 
	 * @throws IllegalBlockSizeException 
	 * @throws InvalidAlgorithmParameterException 
	 * @throws InvalidKeySpecException 
	 * @throws NoSuchPaddingException 
	 * @throws NoSuchAlgorithmException 
	 * @throws InvalidKeyException 
	 * @throws IOException 
	 */
	protected String getJsonStrByParam(String stationId, String params) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, 
	InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException{
		return new String(ThreeDESUtil.des3DecodeCBC(getDynamicKeyBystationId(stationId), 
				keyiv, new BASE64Decoder().decodeBuffer(params)),"UTF-8");
//		return params;
	}
	
	/**
	 * 获取站点动态密钥
	 * @param stationId
	 * @return
	 * @throws IOException 
	 * @throws UnsupportedEncodingException 
	 */
	protected byte[] getDynamicKeyBystationId(String stationId) throws UnsupportedEncodingException, IOException {
		Object o = redisManager.get(String.format(STATION_DYNATIC_KEY, stationId));
		if(o == null){
			StationLoginTO loginTo = loginMapper.getStationLoginTO(stationId);
			redisManager.set(String.format(STATION_DYNATIC_KEY, stationId), loginTo.getDynamicKey());
			return new BASE64Decoder().decodeBuffer(ThreeDESUtil.buildKey(loginTo.getDynamicKey().getBytes()));
		}else{
			return new BASE64Decoder().decodeBuffer(ThreeDESUtil.buildKey(o.toString().getBytes()));
		}
	}
}
